package com.yonyou.ucf.mdf.app.isvdxq.other.controller;

import com.yonyou.iuap.yms.param.SQLParameter;
import com.yonyou.ucf.mdf.app.isvdxq.ReturnResult.DataResult;
import com.yonyou.ucf.mdf.app.isvdxq.common.DxqConfig;
import com.yonyou.ucf.mdf.app.isvdxq.other.service.*;
import com.yonyou.ucf.mdf.app.isvdxq.utils.RequestTool;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.sql.Connection;
import java.sql.Statement;
import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping(value = {DxqConfig.pre_apiUrl+"/autodata",DxqConfig.pre_pcUrl+"/autodata"})
public class AutoDataController {
    private static final Logger logger = LoggerFactory.getLogger(AutoDataController.class);

    @Autowired
    BaseService baseService;
    @Autowired
    WarehouseService warehouseService;
    @Autowired
    UnitService unitService;
    @Autowired
    ProductService productService;
    @Autowired
    OrgUnitService orgUnitService;
    @Autowired
    TranstypeService transtypeService;
    @Autowired
    private ManageClassService manageClassService;

    @Autowired
    private ProductSKUTempService productSKUTempService;
    @Autowired
    private SqlSessionFactory sqlSessionFactory;



    /**
     * 计量单位 编码为空同步所有
     *
     * @param unitcode 编码
     * @return
     */
    @SneakyThrows
    @RequestMapping("/UnitEntityAuto")
    public DataResult UnitEntityAuto(HttpServletRequest request, String unitcode) {
        DataResult result = new DataResult(0, "操作失败");
        try {
//            ContentBean bean = new ContentBean();
//            EventContent content=new EventContent();
//            String mytxt = "{\"_realtype\":\"true\",\"_entityName\":\"pc.product.Product\",\"_keyName\":\"id\",\"modifier\":\"魏宪民\",\"transType_Name\":\"通用物料\",\"modifierId\":2022275112605581324,\"dimensionCode\":\"https://mall-dbox.yonyoucloud.com/detail&goods_id=2045185421647282176\",\"source\":0,\"isRegistrationManager\":false,\"modifyTime\":\"2024-09-03 16:29:24\",\"productApplyRange\":[],\"model\":{},\"productPropCharacterDefine\":{\"_entityName\":\"pc.product.ProductPropCharacterDefine\",\"_keyName\":\"id\",\"_status\":\"Insert\",\"id\":\"2080071250543116295\",\"ytenant\":\"eeyoi5tl\"},\"id\":2045185421647282176,\"isCreator\":true,\"tenant\":3857179605196512,\"isDerivedMaterial\":0,\"creatorType\":0,\"modifyDate\":\"2024-09-03 16:29:24\",\"unitUseType\":2,\"realProductAttribute\":1,\"_status\":\"Update\",\"modelDescription\":{},\"platFormStaus\":1,\"unit\":2022293658286948359,\"transType\":\"2022295728450700557\",\"isEnabled\":true,\"name\":{\"zh_CN\":\"测试物料01\"},\"detail\":{\"_realtype\":\"true\",\"_entityName\":\"pc.product.ProductExtend\",\"_keyName\":\"id\",\"planMethod\":0,\"demandConsolidationDateType\":0,\"saleChannelOfOfflineRetail\":true,\"keySubPart\":false,\"isOfflineStoreOrder\":true,\"modifierId\":2022275112605581324,\"exemption\":false,\"testRule\":1,\"businessAttributeSelfCreate\":0,\"fixedReturn\":false,\"projectTrackStrategy\":0,\"checkByCost\":false,\"depositPayType\":0,\"isExpiryDateManage\":false,\"requireUnit\":2022293658286948359,\"purchasePriceUnit\":2022293658286948359,\"reservation\":false,\"iStatus\":false,\"id\":2045185421647282183,\"isProcess\":false,\"enableSubscribe\":false,\"isCreator\":true,\"tenant\":3857179605196512,\"billingUnit\":2022293658286948359,\"productionMode\":1,\"productId\":2045185421647282176,\"specialCarTransport\":false,\"virtualProductAttribute\":0,\"warehousingByResult\":false,\"businessAttribute\":\"1,7\",\"_status\":\"Update\",\"productLoadWay\":[],\"stockUnit\":2022293658286948359,\"strategyComparisonRule\":0,\"purchaseUnit\":2022293658286948359,\"checkByBatch\":false,\"saleChannel\":\"1,2,3\",\"allowNegativeInventory\":false,\"batchPriceUnit\":2022293658286948359,\"checkByClient\":0,\"retailPriceDimension\":1,\"manageByInventory\":0,\"displayName\":{\"zh_CN\":\"测试物料01\"},\"utility\":false,\"materialCost\":false,\"weighingMode\":0,\"reviewGrossWeight\":false,\"isAllArea\":false,\"specialMaterials\":false,\"serviceDurationUnit\":1,\"deliverQuantityChange\":1,\"productParameters\":[],\"periodicalInspection\":false,\"isBatchManage\":false,\"supplyType\":0,\"stopstatus\":false,\"createDate\":\"2024-07-18 00:00:00\",\"businessAttributeOutSourcing\":0,\"saleChannelOfOnlineBatch\":true,\"inspectionType\":0,\"allowStorePurchase\":true,\"overSigning\":0,\"demandConsolidationUnit\":0,\"onlineUnit\":2022293658286948359,\"businessAttributePurchase\":1,\"lossType\":0,\"isCheckFree\":0,\"BOMType\":0,\"batchUnit\":2022293658286948359,\"supplyDemandPolicy\":0,\"iUOrderStatus\":false,\"virtualPart\":false,\"isRecommend\":false,\"saleChannelOfDistribution\":false,\"mtoStrategy\":0,\"enableSparePartsManagement\":0,\"modifier\":\"魏宪民\",\"iEnableEcontract\":false,\"offlineUnit\":2022293658286948359,\"ECNControl\":false,\"checkByProject\":0,\"logisticsRelated\":false,\"directProduction\":0,\"modifyTime\":\"2024-09-03 16:29:24\",\"onlyOrder\":false,\"isSerialNoManage\":false,\"atpInspection\":0,\"isPriceChangeAllowed\":false,\"productTagNew\":[],\"modifyDate\":\"2024-09-03 16:29:24\",\"saleChannelOfOnlineRetail\":true,\"isBarcodeManage\":false,\"iEnableCyclePurchase\":false,\"accountingByItem\":false,\"bindCarrier\":false,\"checkBySalesOrders\":0,\"depositDealPayType\":0,\"isWeight\":false,\"inspectionUnit\":2022293658286948359,\"produceUnit\":2022293658286948359,\"weigh\":false,\"demandPlanningUnit\":2022293658286948359,\"isSaleInOfflineStore\":true,\"businessAttributeSale\":1,\"checkByRevenueManagement\":0,\"canOrder\":false,\"valueManageType\":0,\"fullSetInspection\":0,\"demandConsolidationType\":0,\"productApplyRangeId\":2045185421647282182,\"orderAdvanceTime\":0,\"isOfflineStoreReturn\":true,\"batchPolicy\":0,\"demandConsolidation\":0,\"isDisplayPrice\":true,\"checkByOutsourcing\":0,\"enablemodifyDeposit\":false,\"ytenant\":\"eeyoi5tl\",\"batchRule\":0,\"returnsWarehousingByResult\":false,\"canSale\":true,\"salesReturnsExemption\":false,\"saleStyle\":\"1\",\"isMaterial\":false,\"enableDeposit\":false,\"demandConsolidationNumber\":1,\"prepareFeed\":false,\"scanCountUnit\":0},\"_convert_detail\":\"ok\",\"useSku\":1,\"orgId_Code\":\"global00\",\"productFamily\":0,\"isAuthorizationManager\":false,\"shop\":-1,\"code\":\"6963000001\",\"isBatch\":0,\"realProductAttributeType\":1,\"orgId\":\"666666\",\"productApplyRange_OrgId\":\"666666\",\"productApplyRangeId\":\"2045185421647282182\",\"salesAndOperations\":0,\"defaultSKUId\":2045185421647282190,\"manageClass\":2045184794582056963,\"isApplied\":true,\"pubts\":\"2024-09-03 16:10:49\",\"productDepositTimeDetail\":[{\"_realtype\":\"true\",\"_entityName\":\"pc.product.ProductDepositTimeDetail\",\"_keyName\":\"id\",\"productId\":2045185421647282176,\"dateRange\":[null,null],\"ytenant\":\"eeyoi5tl\",\"iControlTime\":false,\"_status\":\"Update\",\"productApplyRangeId\":2045185421647282182,\"id\":2045185421647282184,\"ControlTimeType\":0,\"isCreator\":true,\"productDetailId\":2045185421647282183,\"tenant\":3857179605196512}],\"_convert_productDepositTimeDetail\":\"ok\",\"createDate\":\"2024-07-18 00:00:00\",\"productDetail\":[{\"_realtype\":\"true\",\"_entityName\":\"pc.product.ProductDetail\",\"_keyName\":\"id\",\"planMethod\":0,\"demandConsolidationDateType\":0,\"saleChannelOfOfflineRetail\":true,\"keySubPart\":false,\"isOfflineStoreOrder\":true,\"modifierId\":2022275112605581324,\"exemption\":false,\"testRule\":1,\"businessAttributeSelfCreate\":0,\"fixedReturn\":false,\"projectTrackStrategy\":0,\"checkByCost\":false,\"depositPayType\":0,\"isExpiryDateManage\":false,\"requireUnit\":2022293658286948359,\"purchasePriceUnit\":2022293658286948359,\"reservation\":false,\"iStatus\":false,\"id\":2045185421647282183,\"isProcess\":false,\"enableSubscribe\":false,\"isCreator\":true,\"tenant\":3857179605196512,\"billingUnit\":2022293658286948359,\"productionMode\":1,\"productId\":2045185421647282176,\"specialCarTransport\":false,\"virtualProductAttribute\":0,\"warehousingByResult\":false,\"businessAttribute\":\"1,7\",\"_status\":\"Update\",\"productLoadWay\":[],\"stockUnit\":2022293658286948359,\"strategyComparisonRule\":0,\"purchaseUnit\":2022293658286948359,\"checkByBatch\":false,\"saleChannel\":\"1,2,3\",\"allowNegativeInventory\":false,\"batchPriceUnit\":2022293658286948359,\"checkByClient\":0,\"retailPriceDimension\":1,\"manageByInventory\":0,\"displayName\":{\"zh_CN\":\"测试物料01\"},\"utility\":false,\"materialCost\":false,\"weighingMode\":0,\"reviewGrossWeight\":false,\"isAllArea\":false,\"specialMaterials\":false,\"serviceDurationUnit\":1,\"deliverQuantityChange\":1,\"productParameters\":[],\"periodicalInspection\":false,\"isBatchManage\":false,\"supplyType\":0,\"stopstatus\":false,\"createDate\":\"2024-07-18 00:00:00\",\"businessAttributeOutSourcing\":0,\"saleChannelOfOnlineBatch\":true,\"inspectionType\":0,\"allowStorePurchase\":true,\"overSigning\":0,\"demandConsolidationUnit\":0,\"onlineUnit\":2022293658286948359,\"businessAttributePurchase\":1,\"lossType\":0,\"isCheckFree\":0,\"BOMType\":0,\"batchUnit\":2022293658286948359,\"supplyDemandPolicy\":0,\"iUOrderStatus\":false,\"virtualPart\":false,\"isRecommend\":false,\"saleChannelOfDistribution\":false,\"mtoStrategy\":0,\"enableSparePartsManagement\":0,\"modifier\":\"魏宪民\",\"iEnableEcontract\":false,\"offlineUnit\":2022293658286948359,\"ECNControl\":false,\"checkByProject\":0,\"logisticsRelated\":false,\"directProduction\":0,\"modifyTime\":\"2024-09-03 16:29:24\",\"onlyOrder\":false,\"isSerialNoManage\":false,\"atpInspection\":0,\"isPriceChangeAllowed\":false,\"productTagNew\":[],\"modifyDate\":\"2024-09-03 16:29:24\",\"saleChannelOfOnlineRetail\":true,\"isBarcodeManage\":false,\"iEnableCyclePurchase\":false,\"accountingByItem\":false,\"bindCarrier\":false,\"checkBySalesOrders\":0,\"depositDealPayType\":0,\"isWeight\":false,\"inspectionUnit\":2022293658286948359,\"produceUnit\":2022293658286948359,\"weigh\":false,\"demandPlanningUnit\":2022293658286948359,\"isSaleInOfflineStore\":true,\"businessAttributeSale\":1,\"checkByRevenueManagement\":0,\"canOrder\":false,\"valueManageType\":0,\"fullSetInspection\":0,\"demandConsolidationType\":0,\"productApplyRangeId\":2045185421647282182,\"orderAdvanceTime\":0,\"isOfflineStoreReturn\":true,\"batchPolicy\":0,\"demandConsolidation\":0,\"isDisplayPrice\":true,\"checkByOutsourcing\":0,\"enablemodifyDeposit\":false,\"ytenant\":\"eeyoi5tl\",\"batchRule\":0,\"returnsWarehousingByResult\":false,\"canSale\":true,\"salesReturnsExemption\":false,\"saleStyle\":\"1\",\"isMaterial\":false,\"enableDeposit\":false,\"demandConsolidationNumber\":1,\"prepareFeed\":false,\"scanCountUnit\":0}],\"_convert_productDetail\":\"ok\",\"ytenant\":\"eeyoi5tl\",\"manageClass_Code\":\"000001\",\"time\":{\"_realtype\":\"true\",\"_entityName\":\"pc.product.ProductDepositTimeExtend\",\"_keyName\":\"id\",\"productId\":2045185421647282176,\"dateRange\":[null,null],\"ytenant\":\"eeyoi5tl\",\"iControlTime\":false,\"_status\":\"Update\",\"productApplyRangeId\":2045185421647282182,\"id\":2045185421647282184,\"ControlTimeType\":0,\"isCreator\":true,\"productDetailId\":2045185421647282183,\"tenant\":3857179605196512},\"_convert_time\":\"ok\",\"isOptionalMaterial\":0,\"productBarCodes\":[],\"eventNotify_status\":\"Update\",\"_convert_productskus\":\"ok\",\"_convert_productspecitems\":\"ok\"}";
//            bean.setArchive(mytxt);
//            content.setContent(JSONObject.toJSONString(bean));
//            productService.AutoDataEdit(content);
            String tenantId = baseService.getTenantId(request);
            if (StringUtils.isBlank(tenantId)) return result;
            int rInt = unitService.EventProductUnitEdit(tenantId, "code", unitcode);
            result = new DataResult(1, "操作成功");
            result.setData(rInt);
        } catch (Exception ex) {
            result.setMessage(ex.getMessage());
        }
        return result;
    }


    /**
     * 仓库数据同步
     * key val 可为空同步所有
     * 仅更新本地货位表仓库信息
     * 前台手动触发 货位表关联数据同步 调用 WarehouseEntityAutoNextById
     *
     * @param key
     * @param val
     * @return
     */
    @RequestMapping("/WarehouseEntityAuto")
    public DataResult WarehouseEntityAuto(HttpServletRequest request, String key, String val) {
        DataResult result = new DataResult(0, "操作失败");
        try {
            String tenantId = baseService.getTenantId(request);
            if (StringUtils.isBlank(tenantId)) return result;
            String userId = RequestTool.getHeaderAndParameter(request, DxqConfig.DXQ_userId);
            int rInt = warehouseService.EventProductEdit(tenantId, key, val, userId);
            result = new DataResult(1, "操作成功");
            result.setData(rInt);
        } catch (Exception ex) {
            result.setMessage(ex.getMessage());
        }
        return result;
    }

    /**
     * 自动同步执行仓库Id 数据 仅更新本地货位表仓库信息
     * 货位表关联数据同步 调用 WarehouseEntityAutoNextById
     *
     * @param detailId
     * @return
     */
    @RequestMapping("/WarehouseEntityAutoById")
    public DataResult WarehouseEntityAutoById(HttpServletRequest request, @NotNull String detailId) {
        DataResult result = new DataResult(0, "操作失败");
        try {
            String tenantId = baseService.getTenantId(request);
            if (StringUtils.isBlank(tenantId)) return result;
            String userId = RequestTool.getHeaderAndParameter(request, DxqConfig.DXQ_userId);
            int rInt = warehouseService.EventProductEditById(tenantId, detailId, userId);
            result = new DataResult(1, "操作成功");
            result.setData(rInt);
        } catch (Exception ex) {
            result.setMessage(ex.getMessage());
        }
        return result;
    }

    /**
     * 指定仓库Id 数据同步 本地货位表数据关联信息
     * 仓库更新后，触发货位表数据更新
     *
     * @param detailId
     * @return
     */
    @RequestMapping("/WarehouseEntityAutoNextById")
    public DataResult WarehouseEntityAutoNextById(HttpServletRequest request, @NotNull String detailId) {
        DataResult result = new DataResult(0, "操作失败");
        try {
            String tenantId = baseService.getTenantId(request);
            if (StringUtils.isBlank(tenantId)) return result;
            if (StringUtils.isEmpty(detailId)) return result;
            warehouseService.W2LocationById(tenantId, detailId);
            result = new DataResult(1, "操作成功");
        } catch (Exception ex) {
            result.setMessage(ex.getMessage());
        }
        return result;
    }

    /**
     * 组织单位 存在更新，不存在新增
     *
     * @return
     */
    @RequestMapping("/OrgunitEntityAuto")
    public DataResult OrgunitEntityAuto(HttpServletRequest request) {
        DataResult result = new DataResult(0, "操作失败");
        try {
            String tenantId = baseService.getTenantId(request);
            if (StringUtils.isBlank(tenantId)) return result;
            int rInt = orgUnitService.EventItemEdit(tenantId);
            result = new DataResult(1, "操作成功");
            result.setData(rInt);
        } catch (Exception ex) {
            result.setMessage(ex.getMessage());
        }
        return result;
    }

    /**
     * 交易类型 指定Id加载同步
     *
     * @param detailId
     * @return
     */
    @RequestMapping("/TranstypeEntityAuto")
    public DataResult TranstypeEntityAuto(HttpServletRequest request, @NotNull String detailId) {
        DataResult result = new DataResult(0, "操作失败");
        try {
            String tenantId = baseService.getTenantId(request);
            if (StringUtils.isBlank(tenantId)) return result;
            int rInt = transtypeService.EventItemEdit(tenantId, detailId);
            result = new DataResult(1, "操作成功");
            result.setData(rInt);
        } catch (Exception ex) {
            result.setMessage(ex.getMessage());
        }
        return result;
    }

    /**
     * 物料分类 根据Id 同步 /apidxq/isv2/autodata/ProductClassAuto?detailId=
     *
     * @param request
     * @param detailId
     * @return
     */
    @SneakyThrows
    @RequestMapping("/ProductClassAutoById")
    public DataResult ProductClassAutoById(HttpServletRequest request, @NotNull String detailId) {
        DataResult result = new DataResult(0, "操作失败");
        String tenantId = baseService.getTenantId(request);
        if (StringUtils.isBlank(tenantId)) return result;
        //物料分类
        manageClassService.EventManageClassEdit(detailId, tenantId);
        result = new DataResult(1, "操作成功");
        return result;
    }

    /**
     * 物料分类同步
     *
     * @param request
     * @return
     */
    @RequestMapping("/ProductClassAuto")
    @SneakyThrows
    public DataResult ProductClassAuto(HttpServletRequest request) {
        DataResult result = new DataResult(0, "操作失败");
        String tenantId = baseService.getTenantId(request);
        if (StringUtils.isBlank(tenantId)) return result;
        //物料分类
        manageClassService.EventManageClassEditTree("", tenantId);
        result = new DataResult(1, "操作成功");
        return result;
    }

    /**
     * 物料SKU档案 同步
     *
     * @param request
     * @return
     */
    @RequestMapping("/ProductSKUAuto")
    @SneakyThrows
    public DataResult ProductSKUAuto(HttpServletRequest request) {
        DataResult result = new DataResult(0, "操作失败");
        try {
            String tenantId = baseService.getTenantId(request);
            if (StringUtils.isBlank(tenantId)) return result;
            int rInt = productSKUTempService.EventProductSKUEdit(tenantId, null);
            result = new DataResult(1, "操作成功");
        } catch (Exception ex) {
            result.setMessage(ex.getMessage());
        }
        return result;
    }

    /**
     * 物料档案
     * 同步档案，自动关联同步档案分类、档案SKU
     * 分解处理同步问题：分类同步、SKU同步、档案同步
     *
     * @return
     */
    @RequestMapping("/ProductEntityAuto")
    public DataResult ProductEntityAuto(HttpServletRequest request) {
        DataResult result = new DataResult(0, "操作失败");
        try {
            String tenantId = baseService.getTenantId(request);
            if (StringUtils.isBlank(tenantId)) return result;
            int rInt = productService.EventProductEdit(tenantId);
            result = new DataResult(1, "操作成功");
            result.setData(rInt);
        } catch (Exception ex) {
            result.setMessage(ex.getMessage());
        }
        return result;
    }

    /**
     * 档案测试
     * @param request
     * @return
     */
    @SneakyThrows
    @RequestMapping("/AutoDataEditById")
    public DataResult AutoDataEditById(HttpServletRequest request) {
        DataResult result = new DataResult(1, "操作成功");
        String tenantId = baseService.getTenantId(request);
        if (StringUtils.isBlank(tenantId)) return result;
        String productApplyRangeId = "666666";
        String detailId = request.getParameter("id");
        if (!StringUtils.isEmpty(detailId)) {
            productService.AutoDataEditById(detailId, productApplyRangeId, tenantId);
        }
        String productCode = request.getParameter("code");
        if (!StringUtils.isEmpty(productCode)) {
            productService.AutoDataEditNextByCode(productCode, productApplyRangeId, tenantId);
        }
        return result;
    }
    /**
     * 档案批量主动加载
     * @param request
     * @return
     * @throws IOException
     */
    @RequestMapping("/EventProductEdit")
    public DataResult EventProductEdit(HttpServletRequest request) {
        DataResult result = new DataResult(0, "操作失败");
        String tenantId = baseService.getTenantId(request);
        String detailId = request.getParameter("id");
        List<String> ids = Arrays.asList(detailId.split(","));
        try {
            int rInt = productService.EventProductEdit(tenantId, ids);
            result = new DataResult(1, "操作成功");
            result.setData(rInt);
        } catch (Exception ex) {
            result.setMessage(ex.getMessage());
        }

        return result;
    }

    /**
     * 清理私有基础数据
     *
     * @param request 1、初始化组织权限；dxqyy_orgbase、dxqyy_orgunit
     *                2、初始化仓库；dxqyy_warehouse
     *                3、初始化计量单位；dxqyy_unit、dxqyy_unitassist
     *                4、初始化档案分类，档案，SKU档案；dxqyy_product、dxqyy_productskutemp、dxqyy_manageclass
     * @return
     */
    @RequestMapping("/BaseDataClear")
    public DataResult BaseDataClear(HttpServletRequest request) {
        DataResult result = new DataResult(0, "操作失败");
        try {
            String tenantId = baseService.getTenantId(request);
            if (StringUtils.isBlank(tenantId)) return result;
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append(String.format("delete from dxqyy_orgbase where ytenant_id='%s';", tenantId));
            stringBuilder.append(String.format("delete from dxqyy_orgunit where ytenant_id='%s';", tenantId));
            stringBuilder.append(String.format("delete from dxqyy_warehouse where ytenant_id='%s';", tenantId));
            stringBuilder.append(String.format("delete from dxqyy_unit where ytenant_id='%s';", tenantId));
            stringBuilder.append(String.format("delete from dxqyy_unitassist where ytenant_id='%s';", tenantId));
            stringBuilder.append(String.format("delete from dxqyy_product where ytenant_id='%s';", tenantId));
            stringBuilder.append(String.format("delete from dxqyy_productskutemp where ytenant_id='%s';", tenantId));
            stringBuilder.append(String.format("delete from dxqyy_manageclass where ytenant_id='%s';", tenantId));
            SqlSession SqlHelper = sqlSessionFactory.openSession(ExecutorType.BATCH, false);
            String sql = stringBuilder.toString();
            Connection connection = SqlHelper.getConnection();
            Statement statement = connection.createStatement();
            statement.execute(sql);
            SqlHelper.commit();
            connection.close();
            result = new DataResult(1, "操作成功");
        } catch (Exception ex) {
            result.setMessage(ex.getMessage());
        }
        return result;
    }

    /**
     * 清理私有基础业务数据
     *
     * @param request 5、添加智能货位信息；dxq_location
     *                6、添加手持设备用户；dxqyy_userstaff
     *                7、添加设备信息；isv_devicelist isv_devicelog
     *                8、添加基础配置信息；isv_videolog
     * @return
     */
    @RequestMapping("/BaseDataClearBusiness")
    public DataResult BaseDataClearBusiness(HttpServletRequest request) {
        DataResult result = new DataResult(0, "操作失败");
        try {
            String tenantId = baseService.getTenantId(request);
            if (StringUtils.isBlank(tenantId)) return result;
            StringBuilder stringBuilder = new StringBuilder();
            SQLParameter parameter = new SQLParameter(true);
            stringBuilder.append(String.format("delete from isv_devicelist where ytenant_id= ?;"));
            parameter.addParam(tenantId);
            stringBuilder.append(String.format("delete from isv_devicelog where ytenant_id= ?;"));
            parameter.addParam(tenantId);
            stringBuilder.append(String.format("delete from isv_videolog where ytenant_id= ?;"));
            parameter.addParam(tenantId);
            SqlSession SqlHelper = sqlSessionFactory.openSession(ExecutorType.BATCH, false);
            String sql = stringBuilder.toString();
            warehouseService.ExeSQL(sql, parameter);
            SqlHelper.commit();
            result = new DataResult(1, "操作成功");
        } catch (Exception ex) {
            result.setMessage(ex.getMessage());
        }
        return result;
    }
    @RequestMapping("/BaseDataClearLocation")
    public DataResult BaseDataClearLocation(HttpServletRequest request) {
        DataResult result = new DataResult(0, "操作失败");
        try {
            String tenantId = baseService.getTenantId(request);
            if (StringUtils.isBlank(tenantId)) return result;
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append(String.format("delete from dxq_location where ytenant_id='%s';", tenantId));
            stringBuilder.append(String.format("delete from dxqyy_userstaff where ytenant_id='%s';", tenantId));
            SqlSession SqlHelper = sqlSessionFactory.openSession(ExecutorType.BATCH, false);
            String sql = stringBuilder.toString();
            Connection connection = SqlHelper.getConnection();
            Statement statement = connection.createStatement();
            statement.execute(sql);
            SqlHelper.commit();
            connection.close();
            result = new DataResult(1, "操作成功");
        } catch (Exception ex) {
            result.setMessage(ex.getMessage());
        }
        return result;
    }
    /**
     * 轻量化一键部署初始化
     * 业务操作时时检测更新档案、辅助计量等信息
     */
    @RequestMapping("/WMSInit")
    public DataResult WMSInit(HttpServletRequest request) {
        DataResult result = new DataResult(0, "操作失败");
        try {
            //接收参数
            String tenantId = baseService.getTenantId(request);
            result = OrgunitEntityAuto(request);
            if (result.getStatus() != 1) return result;
            logger.info("[OrgunitEntityAuto]" + result.getData());
            result = WarehouseEntityAuto(request, "", "");
            if (result.getStatus() != 1) return result;
            logger.info("[WarehouseEntityAuto]" + result.getData());
            result = UnitEntityAuto(request, "");
            if (result.getStatus() != 1) return result;
            logger.info("[UnitEntityAuto]" + result.getData());
            result = new DataResult(1, "操作成功");
        } catch (Exception ex) {
            String logtxt = "[WMSInit]" + ex.getMessage();
            logger.error(logtxt);
            System.out.println(logtxt);
            result.setMessage(logtxt);
        }
        return result;
    }

    // 入库单据 同步物料信息，仓库信息
//    @RequestMapping("/WMSInitDataByOrder")
//    public DataResult WMSInitDataByOrder(@RequestBody Map<String, Object> paramData, String warehouseId,
//                                         HttpServletRequest request) throws IOException {
//        DataResult result = new DataResult(1, "操作成功");
//        //接收参数
//        String tenantId = baseService.getTenantId(request);
//        String userId = RequestTool.getHeaderAndParameter(request, DxqConfig.DXQ_userId);
//        List<String> ids = (List<String>) paramData.get("ids");
//        List<String> productIds = (List<String>) paramData.get("productIds");
//        result = AutoDataByOrder(productIds, warehouseId, tenantId, userId);
//        return result;
//    }

//    public DataResult AutoDataByOrder(List<String> productIds, String warehouseId, String tenantId, String userId)
//            throws IOException {
//        DataResult result = new DataResult(0, "操作失败");
//        try {
//            if (!StringUtils.isEmpty(warehouseId)) {
//                int rInt_warehouse = warehouseService.EventProductEditById(tenantId, warehouseId, userId);
//                logger.info("[WarehouseEntityAuto]" + rInt_warehouse);
//                System.out.println(rInt_warehouse);
//            }
//            if (productIds != null && productIds.size() > 0) {
//                productIds = productIds.stream().distinct().collect(Collectors.toList());
//                int rInt = productService.EventProductEdit(tenantId, productIds);
//                logger.info("[ProductEntityAuto]" + rInt);
//                System.out.println(rInt);
//            }
//            result = new DataResult(1, "操作成功");
//        } catch (Exception ex) {
//            String logtxt = "[AutoDataByOrder]" + ex.getMessage();
//            logger.error(logtxt);
//            System.out.println(logtxt);
//            result.setMessage(logtxt);
//        }
//        return result;
//    }

}
